package com.example.network_lib;

import com.example.base.utils.LogUtil;

import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author Administrator
 * @createTime 2019/9/25 11:47
 */
public class RetrofitUtils {
    private static HttpApi mApi;

    public static HttpApi getApiInstance() {
        if (mApi == null) {
            synchronized (RetrofitUtils.class) {
                if (mApi == null) {
                    mApi = new RetrofitUtils().getRetrofit();
                }
            }
        }
        return mApi;
    }

    private HttpApi getRetrofit() {
        HttpApi httpApi = initRetrofit(initOkHttp()).create(HttpApi.class);
        return httpApi;
    }

    private Retrofit initRetrofit(OkHttpClient client) {
        return new Retrofit.Builder()
                .client(client)
                .baseUrl(Constants.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private OkHttpClient initOkHttp() {
        OkHttpClient.Builder build = new OkHttpClient().newBuilder()
                .readTimeout(Constants.DEFAULT_TIME, TimeUnit.SECONDS)
                .connectTimeout(Constants.DEFAULT_TIME, TimeUnit.SECONDS)
                .writeTimeout(Constants.DEFAULT_TIME, TimeUnit.SECONDS)
                .addInterceptor(new LogInterception())
                .retryOnConnectionFailure(true);

        OkHttpClient with = RetrofitUrlManager.getInstance().with(build).build();
        return with;
    }

    private class LogInterception implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            LogUtil.d("request:" + request.toString());
            long t1 = System.nanoTime();
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
            LogUtil.d("okhttp logInterception--  " + String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers()));
            MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            LogUtil.d("response:" + content);
            return response.newBuilder()
                    .body(ResponseBody.create(mediaType, content))
                    .build();

        }
    }
}
